package cn.web;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;

//@WebFilter(value = "/*", initParams = { @WebInitParam(name = "encoding", value = "utf-8") })
public class EncodingFilter implements Filter {
	private String encoding = "utf-8";
	private boolean force = false;

	@Override
	public void destroy() {

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		System.out.println("进入了字符集过滤器");
		// 之前字符集.
		System.out.println("强制：" + force + ",字符集是：" + this.encoding);
		if (this.force) {
			request.setCharacterEncoding(this.encoding);
			response.setContentType("text/html;charset=" + this.encoding);
		}
		chain.doFilter(request, response);
		System.out.println("离开了字符集过滤器");
	}

	// config
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		this.encoding = filterConfig.getInitParameter("encoding");
		this.force = Boolean.parseBoolean(filterConfig.getInitParameter("force"));
	}

}
